package com.suning.framework.ImportMpsInfo;

import com.suning.framework.utils.EsUtils;
import com.suning.framework.Mps_member_portrait_info;
import com.suning.framework.utils.JsonDateValueProcessor;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author 16080951(林健)
 * @Copyright (c) 2016 苏宁软件技术有限公司 版权所有
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class ImportMps {

    //索引
    private final static String INDEX = "suning";

    //类型
    private final static String TYPE = "portait";

    /**
     * 存es
     * XPOST 'localhost:9200/xxx/_bulk?pretty' -d '{}'
     */
    public void setInfo(List<Mps_member_portrait_info> list) {

        Client client = EsUtils.openConnection();
        BulkRequestBuilder bulkRequest = client.prepareBulk();

        JsonConfig config = new JsonConfig();
        //对时间进行自定义
        config.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor("yyyy-MM-dd"));
        //对有空的，null的，不要参与序列化
        config.setJsonPropertyFilter(new PropertyFilter() {
            @Override
            public boolean apply(Object o, String s, Object o1) {
                return o1 == null || "".equals(o1);
            }
        });
        for (Mps_member_portrait_info portraitInfo : list) {
            bulkRequest.add(
                    client.prepareIndex(INDEX, TYPE, portraitInfo.getAcct_no())
                            .setSource(JSONObject.fromObject(portraitInfo,config).toString())
            );
        }

        int k = bulkRequest.get().getItems().length;
        //System.out.println("开始存入ES共 --->" + k + "条。");
        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
        if (bulkResponse.hasFailures()) {
            //处理错误
            System.out.println("处理错误！！！");
        }
        client.close();
    }



    /**
     * 分页查询
     *
     * @return the list
     */
    public static List<Mps_member_portrait_info> doPageQuery(){
        Client client = EsUtils.openConnection();

        //每页多少条
        long pageSize = 100;

        //匹配查询,配合.setQuery(queryBuilder)
        //QueryBuilder queryBuilder = new MatchQueryBuilder("acct_no","0000000000033171278");
        //QueryBuilder queryBuilderMap = new HasParentQueryBuilder("acct_no","0000000000033171278");
        //QueryBuilder queryBuilderMap = new HasChildQueryBuilder("acct_no","0000000000033171278");


        SearchResponse searchResponse =
                client.prepareSearch(INDEX)
                        .setTypes(TYPE)
                        .setSearchType(SearchType.DFS_QUERY_AND_FETCH)
                        //.setQuery(queryBuilder)
                        .setScroll(TimeValue.timeValueMinutes(1))
                        .setSize((int)pageSize / 5) //返回条数 = 分片数 * size
                        .execute()
                        .actionGet();


        //总量
        long total = searchResponse.getHits().getTotalHits();
        System.out.println("total : " + total);

        //共多少页
        long totalPage = ( total % pageSize == 0 ) ? total / pageSize : (total / pageSize)+1;

        //当前页
        long currentPage = 1;
        List<SearchHit> result = new ArrayList<SearchHit>();
        while (true) {
            searchResponse = client.prepareSearchScroll(searchResponse.getScrollId())
                    .setScroll(TimeValue.timeValueMinutes(1))
                    .execute()
                    .actionGet();

            if(searchResponse.getHits().hits().length == 0)break;
            else{
                //将所有数据放入List
                Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
                while(iterator.hasNext()){
                    SearchHit hit = iterator.next();
                    result.add(hit);
                }

                if(result.size() > 10000) break;
            }
        }

        //当前result中的总数据量
        System.out.println(result.size());

        //分页取数据
        for(int i = 0 ; i < totalPage && currentPage <= totalPage ;i++ ){

            List _tmp = result.subList((int)((currentPage - 1)*pageSize),(int)((currentPage * pageSize > total ? total : currentPage * pageSize)));
            currentPage++;

        }

        for(SearchHit obj : result){
            String json = obj.getSourceAsString();
            System.out.println(json);
        }
        client.close();
        return null;
    }


    /**
     * 匹配查询
     *
     * @return the list
     */
    public static void doMatchQuery(){
        Client client = EsUtils.openConnection();

        QueryBuilder queryBuilder = new MatchAllQueryBuilder();

        SearchResponse searchResponse =
                client.prepareSearch(INDEX)
                        .setTypes(TYPE)
                        .setSearchType(SearchType.DFS_QUERY_AND_FETCH)
                        .setQuery(queryBuilder)
                        .setTimeout(TimeValue.timeValueMinutes(1))
                        .execute()
                        .actionGet();

        //总量
        long total = searchResponse.getHits().getTotalHits();
        System.out.println("total : " + total);

        //将所有数据放入List
        /*Iterator<SearchHit> iterator = searchResponse.getHits().iterator();
        while(iterator.hasNext()){
            SearchHit hit = iterator.next();
            String json = hit.getSourceAsString();
            System.out.println(json);
        }
*/
        client.close();
    }




    public static void main(String[] args) {
       //匹配查询
        doMatchQuery();
    }
}
